package com.taomu.app.zongchouhuli.moudle.mine.contract.impl;

import com.alibaba.fastjson.JSONObject;
import com.taomu.app.zongchouhuli.entity.BaseChangeResponse;
import com.taomu.app.zongchouhuli.entity.BaseResponse;
import com.taomu.app.zongchouhuli.http.api.HttpObserver;
import com.taomu.app.zongchouhuli.http.api.Request;
import com.taomu.app.zongchouhuli.http.res.ResUserInfoEntity;
import com.taomu.app.zongchouhuli.moudle.mine.contract.GetInfoContract;
import com.taomu.app.zongchouhuli.utils.ParseUtil;
import com.taomu.app.zongchouhuli.utils.StorageHelper;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class GetInfoPresenter implements GetInfoContract.Presenter {

    private GetInfoContract.View mContractView;

    private CompositeDisposable disposable;

    public GetInfoPresenter(GetInfoContract.View mContractView){
        this.mContractView = mContractView;
        this.disposable = new CompositeDisposable();
    }

    @Override
    public void getUserInfo() {
        Request.getIntence().getUserInfo(StorageHelper.getToken())
                .flatMap(new Function<String, ObservableSource<BaseChangeResponse<ResUserInfoEntity>>>() {
                    @Override
                    public ObservableSource<BaseChangeResponse<ResUserInfoEntity>> apply(String json) throws Exception {
                        BaseResponse<JSONObject> baseResponse = ParseUtil.parseObject(json,BaseResponse.class);
                        BaseChangeResponse<ResUserInfoEntity> data = new BaseChangeResponse<>();
                        data.setData(ParseUtil.parseObject(baseResponse.getData().toString(),ResUserInfoEntity.class));
                        data.setCount(baseResponse.getCount());
                        return Observable.just(data);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseChangeResponse<ResUserInfoEntity>>(mContractView,disposable,true) {
                    @Override
                    public void onNext(BaseChangeResponse<ResUserInfoEntity> baseResponse) {
                        if(mContractView != null){
                            StorageHelper.saveToken(baseResponse.getData().getToken());
                            StorageHelper.saveAccountInfo(ParseUtil.toJson(baseResponse.getData()));
                            mContractView.setUserInfo(baseResponse.getData());
                        }
                    }
                });
    }

    @Override
    public void onStart() {

    }

    @Override
    public void onDetch() {

    }
}
